/**
 * 项目名：admin
 * 包名：com.xuebang.admin.controller
 * 文件名：SlideController.java
 * 版本信息：@version 1.0
 * 日期：2014-2-17-下午3:46:14
 */
package com.xuebang.admin.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.xuebang.admin.entity.Links;
import com.xuebang.admin.entity.OperatorRules;
import com.xuebang.admin.service.LinkService;
import com.xuebang.admin.util.JsonUtil;
import com.xuebang.admin.web.Result;

/**
 * 项目名称：admin
 * 类名称：SlideController
 * 类描述：
 * 创建人：xuyang
 * 创建时间：2014-2-17 下午3:46:14
 * 修改人：xuyang
 * 修改时间：2014-2-17 下午3:46:14
 * 修改备注：
 * @version 
 */
@Controller
@RequestMapping("/slide")
public class SlideController extends BaseController{
	

	@Inject
	LinkService linkService; 
	
	/**
	 * 展示所有的幻灯片
	 */
	@RequestMapping(value="/showSlides")
	public String showSlides(Model model){
		
		List<Links> links = this.linkService.showSlides();
		if(links==null){
			links = new ArrayList<Links>();
		}
		model.addAttribute("links",links);
		return "/slide/showSlides";
	}
	
	/**
	 * 展示所有的
	 */
	@RequestMapping(value="/operate")
	public String operate(Model model){
		
		if(!hasPerm(OperatorRules.PERM_SLIDE)){
			return "/account/no_perm";
		}
		
		return "/slide/operate";
	}
	
	/**
	 * 跳转到增加页面
	 */
	@RequestMapping(value="/add")
	public String add(Links slideLink,Model model){
		
		model.addAttribute("slideLink",slideLink);
		return "/slide/add";
	}
	
	/**
	 * 跳转到更新页面
	 */
	@RequestMapping(value="/update")
	public String update(Integer linkId,Model model){

		List<Integer> lstSlidesIndex = new ArrayList<Integer>();
		List<Links> links = this.linkService.showSlides();
		Links slideLink = null;
		int i = 1;
		int intFlag = 0;
		//System.out.println("linkId"+linkId);
		for(Links link: links){
			//System.out.println(link.getId());
			if(link.getId().intValue()==linkId){
				slideLink = link;
				intFlag = i;
			}
			lstSlidesIndex.add(i++);
		}
//		System.out.println("=====");
//		System.out.println(intFlag);
		slideLink.setSort(intFlag);
		model.addAttribute("slideLink",slideLink);
		model.addAttribute("lstSlidesIndex",lstSlidesIndex);
		
		return "/slide/update";
	}
	
	/**
	 * 增加幻灯片
	 */
	@RequestMapping(value="/toAdd",method = RequestMethod.POST,produces = "text/plain;charset=UTF-8")
	public String toAdd(@Valid Links slideLink,HttpServletRequest request,Model model){
		
		try{
			// 检查
			String strCheckResult = slideValidate(slideLink);
			if(strCheckResult==""){
				//initSort(slideLink);
				// 自动添加http
				addHttp(slideLink);
				// 上传幻灯片
				String strPath = uploadPic(slideLink.getPicFile(),request);
				if(strPath==null) {
					model.addAttribute("resultType",0);
					model.addAttribute("resultMessage","增加失败");
				} else {
					slideLink.setPic(strPath);
					this.linkService.addLinks(slideLink);
					model.addAttribute("resultType",1);
					model.addAttribute("resultMessage","增加成功");
				}
			} else {
				model.addAttribute("resultType",0);
				model.addAttribute("resultMessage",strCheckResult);
			}
		}catch(Exception e){
			e.printStackTrace();
			model.addAttribute("resultType",0);
			model.addAttribute("resultMessage","增加失败");
			
		}

		model.addAttribute("slideLink",slideLink);
		return "/slide/add";
	}
	
	/**
	 * 更新幻灯片
	 */
	@RequestMapping(value="/toUpdate",method = RequestMethod.POST,produces = "text/plain;charset=UTF-8")
	public String toUpdate(@Valid Links slideLink,HttpServletRequest request,Model model){

		try{
			// 检查
			String strCheckResult = slideValidate(slideLink);
			if(strCheckResult==""){
//				initSort(slideLink);
				// 自动添加http
				addHttp(slideLink);
				// 上传幻灯片
				String strPath = null;
				if(slideLink.getPicFile().getSize()>0){
					deleteFile(slideLink.getPic(),request);
					strPath = uploadPic(slideLink.getPicFile(),request);
				} else if(slideLink.getPic()!=null){
					strPath = slideLink.getPic();
				}
				if(strPath==null) {
					model.addAttribute("resultMessage","更新失败");
					model.addAttribute("resultType",0);
				} else {
					slideLink.setPic(strPath);
					this.linkService.updateLinksItems(slideLink);
					model.addAttribute("resultType",1);
					model.addAttribute("resultMessage","更新成功");
				}
			} else {
				model.addAttribute("resultType",0);
				model.addAttribute("resultMessage",strCheckResult);
			}
		}catch(Exception e){
			e.printStackTrace();
			model.addAttribute("resultType",0);
			model.addAttribute("resultMessage","更新失败");
		}
		//model.addAttribute("slideLink",slideLink);
		if(slideLink!=null&&slideLink.getId()!=null){
			update(slideLink.getId(),model);
		}
		return "/slide/update";
	}
	
	/**
	 * 幻灯片
	 */
	@RequestMapping(value="/toDelete",method = RequestMethod.POST,produces = "text/plain;charset=UTF-8")
	public @ResponseBody String toDelete(String strSlideIds,HttpServletRequest request){
		
		try{
			List<Links> linkList = this.linkService.findLinks(strSlideIds);
			for(Links links:linkList){
				deleteFile(links.getPic(),request);
			}
			this.linkService.deleteLinks(strSlideIds);
			return JsonUtil.dump(Result.success("删除成功"));
		}catch(Exception e){
			e.printStackTrace();
			return JsonUtil.dump(Result.error("删除失败"));
		}
	}
    /**
     * 删除单个文件
     * @param   sPath    被删除文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public void deleteFile(String sPath,HttpServletRequest request) {
    	String basePath = request.getSession().getServletContext().getRealPath("/").replaceAll("\\\\", "/");
    	
        File file = new File(basePath.substring(0, basePath.length()-7)+sPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            System.out.println(sPath+"图片删除成功");
        }
    }
	/**
	 * 改变位置
	 */
	@RequestMapping(value="changePos",method=RequestMethod.POST,produces = "text/plain;charset=UTF-8")
	public @ResponseBody String changePos(Integer slideId,Integer intFlag){
		
		Links slideLink = this.linkService.loadLink(slideId);
		if(slideLink!=null){
			List<Links> lstSlideLinks = this.linkService.showSlides();
			if(lstSlideLinks!=null &&lstSlideLinks.size()>0 ){
				if(lstSlideLinks.size()>1){
					Integer intCurrentIndex = 0;
					// 找出
					int intIndex = 0;
					for(Links tmpMenuColumn:lstSlideLinks){
						if(tmpMenuColumn.getId().intValue()==slideId.intValue()){
							intCurrentIndex = intIndex;
							break;
						}
						intIndex ++;
					}
					Integer intDesIndex = null;
					// 上升
					if(intFlag == 0){
						if(intIndex > 0){
							intDesIndex = intCurrentIndex-1;
						}
					} else {
					// 下降
						if(intIndex < lstSlideLinks.size()-1){
							intDesIndex = intCurrentIndex+1;
						}
					}
					if(intDesIndex!=null){
						try{
							Integer intTmp = lstSlideLinks.get(intDesIndex).getSort();
							lstSlideLinks.get(intDesIndex).setSort(lstSlideLinks.get(intCurrentIndex).getSort());
							lstSlideLinks.get(intCurrentIndex).setSort(intTmp);
							this.linkService.updateLinks(lstSlideLinks.get(intCurrentIndex));
							this.linkService.updateLinks(lstSlideLinks.get(intDesIndex));
							return JsonUtil.dump(Result.success("修改成功"));
						} catch(Exception e){
							return JsonUtil.dump(Result.error("修改失败"));
						}
					} else {
						return JsonUtil.dump(Result.error("修改成功"));
					}
				}  else {
					return JsonUtil.dump(Result.error("修改失败"));
				}
			} else {
				//ERROR
				return JsonUtil.dump(Result.error("修改失败"));
			}
		} else {
			//ERROR
			return JsonUtil.dump(Result.error("修改失败"));
		}
	}
	
	/**
	 * 检查 
	 * 
	 */
	private String slideValidate(Links slideLink){
		
		if(slideLink==null){
			return "表单提交异常";
		}

		String strResult = "";
		// name不能为空
		if(slideLink.getTheme()==null || "".equals(slideLink.getTheme().trim())){
			strResult = "主题不能为空";
		}
		
		// pic不能为空
		if(slideLink.getPicFile().getSize()==0&&
				(slideLink.getPic()==null||"".equals(slideLink.getPic().trim()))){
			if(strResult!=""){
				strResult += "/r/n";
			}
			strResult += "图片不能为空";
		}

		return strResult;
	}
	
	/**
	 * 文件上传
	 * 
	 * @param picFile
	 * 	图片文件
	 * @param request
	 * 	请求
	 */
	private String uploadPic(CommonsMultipartFile picFile,HttpServletRequest request){
		
		String strPicPath = null;
		try{
			// 构建文件保存的目录
			SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMdd");
	        String logoPathDir = "/upload/" + dateformat.format(new Date());
	        // 得到文件保存目录的真实路径
	        String logoRealPathDir = request.getSession().getServletContext()
	                .getRealPath(logoPathDir).replaceAll("\\\\", "/");
	        // 根据真实路径创建目录
	        File logoSaveFile = new File(logoRealPathDir);
	        if (!logoSaveFile.exists())
	            logoSaveFile.mkdirs();

	        // 文件后缀
	        String suffix = picFile.getOriginalFilename().substring(
	        		picFile.getOriginalFilename().lastIndexOf("."));
	        // 文件名=上传文件名+年月日时分秒
	        SimpleDateFormat dat = new SimpleDateFormat("yyyyMMddHHmmss");
	        String strFileName = picFile.getOriginalFilename() + "_" + dat.format(new Date()) + suffix;
			String strRealFileName = logoRealPathDir + "/" + strFileName;
			File file = new File(strRealFileName);
			picFile.transferTo(file);
			//图片加水印logo
			//ImageUtils.pressImage(request.getSession().getServletContext().getRealPath("/images/logo/logo-cn.png").replaceAll("\\\\", "/"), strRealFileName, 0, 0);
			
			strPicPath = request.getContextPath() + logoPathDir + "/" + strFileName;
		}catch(Exception e){
			e.printStackTrace();
		}
		return strPicPath;
	}
	
	/**
	 * 自动添加http
	 */
	private void addHttp(Links adLink){
		
		if(adLink!=null){
			String strUrl = adLink.getUrl();
			if(strUrl!=null&&!"".equals(strUrl.trim())){
				if(!strUrl.contains("http://")&&!strUrl.contains("https://")){
					strUrl="http://" + strUrl;
					adLink.setUrl(strUrl);
				}
			}
		}
	}
	

}
